import { VmoRequest } from "vmo-request";

interface EmbeddingResponse {
  data: {
    embedding: number[];
    model: string;
    created_at: string;
  }
}

export class Embedding{
  private vmoRequest:VmoRequest
  public constructor(baseURL:string){
    this.vmoRequest = new VmoRequest({
      baseURL:baseURL,
      method:'post',
      timeout: 5000,
    })
  }
  public async embedding(text:string):Promise<number[]>{
    try {
      const response = await this.vmoRequest.request({
        method: 'post',
        data: {
          model: 'bge-m3',
          prompt: text,
        }
      }, 1, 3); // 不缓存，失败重试3次
      // console.log(response)
      // 打印响应数据（避免循环引用）
      console.log('API 响应数据:', {
        embedding: response?.data?.embedding.length,
      });
  
      // 验证响应数据
      if (!response || typeof response !== 'object') {
        throw new Error('响应数据格式错误：不是有效的对象');
      }
  
      const embeddingResponse = response as EmbeddingResponse;
      if (!embeddingResponse?.data?.embedding || !Array.isArray(embeddingResponse?.data?.embedding)) {
        throw new Error('响应数据格式错误：embedding 字段不是有效的数组');
      }
  
      return embeddingResponse?.data?.embedding;
    } catch (error) {
      console.error('生成嵌入失败:', error);
      throw new Error(`生成文本嵌入失败: ${error instanceof Error ? error.message : '未知错误'}`);
    }
  }
}